package com.demo.fork.demo1;

import java.util.concurrent.ForkJoinPool;

/**
 * @author : YU.TAN
 * @date : 2021/8/22 22:26
 * 我们设置的计算区间值0~10000000，当计算的个数超过100时，将对任务进行拆分，最大并发数设置为16.
 */
public class TheKingRecursiveSumExcute {
    public static void main(String[] args) {
        int sumBegin=0,sumEnd=100000000;
        computeByForkJoin(sumBegin,sumEnd);
        computeBySingleThread(sumBegin,sumEnd);
    }

    private static void computeByForkJoin(int sumBegin,int sumEnd){
        ForkJoinPool forkJoinPool=new ForkJoinPool(16);
        long startTime = System.nanoTime();
        TheKingRecursiveSumTask task = new TheKingRecursiveSumTask(sumBegin, sumEnd, 10000000);
        Long forkJoinResult = forkJoinPool.invoke(task);
        System.out.println("=======");
        System.out.println("forkJoin任务拆分："+TheKingRecursiveSumTask.getTaskCount());
        System.out.println("ForkJoin计算结果："+forkJoinResult);
        System.out.println("ForkJoin计算耗时："+(System.nanoTime()-startTime)/1000000);
    }

    private static void computeBySingleThread(int sumBegin, int sumEnd) {
        long computeResult = 0L;
        long startTime = System.nanoTime();
        for (int i = sumBegin; i < sumEnd; i++) {
            computeResult += i;
        }
        System.out.println("======");
        System.out.println("单线程计算结果：" + computeResult);
        System.out.println("单线程计算耗时：" + (System.nanoTime() - startTime) / 1000000);

    }
}
